package utils;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * LC: 2022-11-18 16:04
 */
@Configuration
public class RedisConfig {

    @Bean
    RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){

        RedisTemplate<Object,Object> rt = new RedisTemplate<Object,Object>();
        rt.setConnectionFactory(redisConnectionFactory);

        Jackson2JsonRedisSerializer<Object> s = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);
        s.setObjectMapper(objectMapper);

        StringRedisSerializer ss = new StringRedisSerializer();
        rt.setDefaultSerializer(s);

        rt.setKeySerializer(ss);
        rt.setHashKeySerializer(ss);

        rt.setValueSerializer(s);
        rt.setHashValueSerializer(s);

        rt.afterPropertiesSet();
        return rt;
    }
}
